package org.osomit.sacct.io.impl;

import org.stringtree.json.JSONReader;
import org.osomit.sacct.builder.SecureResponseBuilder;
import org.osomit.sacct.entity.SecureResponse;
import org.osomit.sacct.entity.SecureRequest;
import org.osomit.sacct.io.iface.ClientReaderWriter;
import org.osomit.sacct.SAcctException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 * 
 * Date: Jun 29, 2009
 */
public class JSONClientReaderWriter implements ClientReaderWriter {
    private static final String ERROR_READING_RESPONSE = "Error reading response: ";
    private static final String ERROR_SENDING_REQUEST = "Error sending request: ";

    private JSONReader jsreader = new JSONReader();
    
    private SecureResponseBuilder builder = new SecureResponseBuilder();

    public SecureResponse read(BufferedReader reader) {
        try {
            String out = reader.readLine();
            Object obj = jsreader.read(out);
            SecureResponse response = builder.build(obj);

            return response;
        } catch (IOException e) {
            throw new SAcctException(ERROR_READING_RESPONSE + e.getMessage());
        } catch(Exception e){
            throw new SAcctException(ERROR_READING_RESPONSE + e.getMessage());
        }
    }

    public void write(OutputStream outputStream, SecureRequest request) {
        try {
            String resp = request.toJSON().toString() + "\n";
            outputStream.write(resp.getBytes());
            outputStream.flush();
        } catch (IOException e) {
            throw new SAcctException(ERROR_SENDING_REQUEST + e.getMessage());
        }catch(Exception e){
            throw new SAcctException(ERROR_SENDING_REQUEST + e.getMessage());
        }
    }
}
